﻿using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using UniMana.Utils.Data;
using UniMana.Utils.Configs;
using UniMana.Data;

namespace UniMana.Win.Training
{
    public partial class FrmScore_AddStudentSubjectClassCensorship : DevExpress.XtraEditors.XtraForm
    {
        private DBMain m_data = new DBMain();
        private DataTable m_dtList = new DataTable();
        private string m_strIDLogAdd = "";
        private Guid m_gPersonelKey = Guid.Parse(UniMana.Utils.LoginInfo.GblLoginInfo.sysLoginPersionalKey.ToString());
        private bool m_bCheck = false;
        public FrmScore_AddStudentSubjectClassCensorship()
        {
            InitializeComponent();
            LoadData();
        }
        //GridView
        private void grvListLogAdd_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            int rowIndex = e.RowHandle;
            if (rowIndex >= 0)
            {
                rowIndex++;
                e.Info.DisplayText = rowIndex.ToString();
            }
        }
        private void grvListLogAdd_Click(object sender, EventArgs e)
        {
            m_bCheck = true;
            GetInfo();
        }
        private void grvListLogAdd_ShowingEditor(object sender, CancelEventArgs e)
        {
            GetInfo();
            #region [Chap nhan them sinh vien vao lop]
            if (grvListLogAdd.FocusedColumn == gdPermit)
            {
                if ((bool)grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Status"]) == true)
                {
                    m_bCheck = true;
                    XtraMessageBox.Show("Phiếu đã được duyệt!", "Thông báo");
                    txtFeedback.Enabled = false;
                    e.Cancel = true;
                    return;
                }
                else
                {
                    m_bCheck = false;
                    txtFeedback.Enabled = true;
                    DialogResult _diag = XtraMessageBox.Show("Bạn có muốn duyệt phiếu " + grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["logAddID"]).ToString() + "?", "Thông báo", MessageBoxButtons.YesNo);
                    if (_diag == DialogResult.Yes)
                    {
                        //Cap nhat thong tin phieu yeu cau 
                        bool _bValue = (bool)grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Permit"]);
                        grvListLogAdd.SetFocusedRowCellValue(grvListLogAdd.Columns["Permit"], !_bValue);
                        int _iLogAdd = Convert.ToInt32(grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Log_AddStudentSubjectClassKey"]).ToString());
                        Log_AddStudentSubjectClassInfo infoLogAdd = new Log_AddStudentSubjectClassInfo(_iLogAdd);
                        infoLogAdd.Properties.Permit = !_bValue;
                        infoLogAdd.Properties.Status = true;
                        infoLogAdd.Properties.DateCensorship = SysDateTime.Now;
                        infoLogAdd.Properties.PersonelCensorshipKey = m_gPersonelKey;
                        infoLogAdd.Properties.Feedback = txtFeedback.Text;
                        infoLogAdd.Save();
                        //Them vao bang StudentSubjectClass
                        string _strStudentKey = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Training_StudentKey"]).ToString();
                        int _iSubjectClassKey = Convert.ToInt32(grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Training_Subject_ClassKey"]).ToString());
                        int _iProgramKey = Convert.ToInt32(grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Training_TrainingProgramKey"]).ToString());
                        Training_Student_Subject_ClassInfo infoStudentSubjectClass = new Training_Student_Subject_ClassInfo(_strStudentKey, _iSubjectClassKey);
                        infoStudentSubjectClass.Properties.Training_TrainingProgramKey = _iProgramKey;
                        infoStudentSubjectClass.Save();
                        //Them vao bang Score
                        DataTable _dtScoreType = new DataTable();
                        _dtScoreType = m_data.m_DCReadOnly.Training_SubjectClass_ScoreTypes.GetList(_iSubjectClassKey).ToDataTable();
                        if (_dtScoreType.Rows.Count > 0)
                        {
                            for (int i = 0; i < _dtScoreType.Rows.Count; i++)
                            {
                                int _iScoreType = Convert.ToInt32(_dtScoreType.Rows[i]["Training_ScoreTypeKey"].ToString());
                                Training_ScoreInfo infoScore = new Training_ScoreInfo(_strStudentKey, _iSubjectClassKey, _iScoreType);
                                infoScore.Properties.Training_StudentKey = Guid.Parse(_strStudentKey);
                                infoScore.Properties.Training_Subject_ClassKey = _iSubjectClassKey;
                                infoScore.Properties.Training_ScoreTypeKey = _iScoreType;
                                if ((bool)(_dtScoreType.Rows[i]["Lock"]) == true)
                                {
                                    infoScore.Properties.OnlyRead = true;
                                }
                                else
                                {
                                    infoScore.Properties.OnlyRead = false;
                                }
                                infoScore.Properties.Note = "Ngày thêm: " + SysDateTime.Now.ToString("dd/MM/yyyy");
                                infoScore.Save();
                            }
                        }
                        //Load lai du lieu
                        LoadData();
                        #region[Tinh diem trung binh tich luy]
                        // _strStudentID = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["StudentID"]).ToString();
                        //DataTable _dtListScore = new DataTable();
                        //_dtListScore = m_data.m_DCReadOnly.Training_Scores.GetSubjectScoreListofStudentByID(
                        //    m_data.m_DCReadOnly.Training_Subjects,
                        //    m_data.m_DCReadOnly.Training_TrainingProgram_Details,
                        //    m_data.m_DCReadOnly.Training_Student_Subject_Classes,
                        //    m_data.m_DCReadOnly.Training_Subject_Classes,
                        //    m_data.m_DCReadOnly.Training_Students,
                        //    m_data.m_DCReadOnly.Training_Student_Classes,
                        //    m_data.m_DCReadOnly.Catalogue_Terms,
                        //    m_data.m_DCReadOnly.Catalogue_SchoolYears,
                        //    _strStudentID, -1, -1, _iProgramKey).ToDataTable();
                        //caculateAverageScoreAccumulate(_dtListScore, _strStudentID);
                        #endregion
                        e.Cancel = true;
                        return;
                    }
                    else
                    {
                        m_bCheck = false;
                        e.Cancel = true;
                        return;
                    }
                }
            }
            #endregion
            #region [Khong chap nhan them sinh vien vao lop]
            if (grvListLogAdd.FocusedColumn == gdRefuse)
            {
                if ((bool)grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Status"]) == true)
                {
                    m_bCheck = true;
                    XtraMessageBox.Show("Phiếu đã được duyệt!", "Thông báo");
                    txtFeedback.Enabled = false;
                    e.Cancel = true;
                    return;  
                }
                else
                {
                    m_bCheck = false;
                    DialogResult _diag = XtraMessageBox.Show("Bạn có muốn từ chối phiếu " + grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["logAddID"]).ToString() + "?", "Thông báo", MessageBoxButtons.YesNo);
                    if (_diag == DialogResult.Yes)
                    {
                        //Cap nhat thong tin bang phieu yeu cau
                        if (txtFeedback != null && txtFeedback.Text != "")
                        {
                            bool _bValue = (bool)grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Refuse"]);
                            grvListLogAdd.SetFocusedRowCellValue(grvListLogAdd.Columns["Refuse"], !_bValue);
                            int _iLogAdd = Convert.ToInt32(grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Log_AddStudentSubjectClassKey"]).ToString());
                            Log_AddStudentSubjectClassInfo infoLogAdd = new Log_AddStudentSubjectClassInfo(_iLogAdd);
                            infoLogAdd.Properties.Refuse = !_bValue;
                            infoLogAdd.Properties.Status = true;
                            infoLogAdd.Properties.DateCensorship = SysDateTime.Now;
                            infoLogAdd.Properties.PersonelCensorshipKey = m_gPersonelKey;
                            infoLogAdd.Properties.Feedback = txtFeedback.Text;
                            infoLogAdd.Save();
                            LoadData();
                            txtFeedback.Text = "";
                        }
                        else
                        {
                            XtraMessageBox.Show("Thông tin phản hồi không được trống!", "Thông báo");
                        }
                        e.Cancel = true;
                        return;
                    }
                    else
                    {
                        m_bCheck = false;
                        e.Cancel = true;
                        return;
                    }
                }
            }
        #endregion 
        }
        private void grvListLogAdd_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (!this.grvListLogAdd.IsFilterRow(e.RowHandle))
            {
                bool _bStatus = Convert.ToBoolean(grvListLogAdd.GetRowCellValue(e.RowHandle, grvListLogAdd.Columns["Status"]));
                if (_bStatus == true)
                {

                }
                else
                {
                    e.Appearance.BackColor = Color.Orange;
                }
            }
        }
        //Methods
        /// <summary>
        /// Load du lieu
        /// </summary>
        private void LoadData()
        {
            m_dtList = m_data.m_DCReadOnly.Log_AddStudentSubjectClasses.GetList(m_data.m_DCReadOnly.Personnel_Personnels,
                                                m_data.m_DCReadOnly.Training_Students,
                                                m_data.m_DCReadOnly.Training_Subject_Classes,
                                                m_data.m_DCReadOnly.Training_Student_Classes).ToDataTable();
            gctListLogAdd.DataSource = m_dtList;
        }
        /// <summary>
        /// Tinh diem trung binh tich luy
        /// </summary>
        /// <param name="dtInfo"></param>
        /// <param name="strStudentID"></param>
        private void caculateAverageScoreAccumulate(DataTable dtInfo, string  strStudentID)
        {
            DataTable _dtScore = dtInfo;
            string _strStudentId = strStudentID;
            _dtScore.Columns.Add("HPTC");
            double _dCreditAcc = 0;
            double _dScoreAcc = 0;
            double _dCredit = 0;
            double _dScore = 0;
            for (int i = 0; i < _dtScore.Rows.Count; i++)
            {
                _dtScore.Rows[i]["HPTC"] = Convert.ToDouble(_dtScore.Rows[i]["AverageScoreFinal"].ToString()) *
                                        Convert.ToDouble(_dtScore.Rows[i]["TotalCredits"].ToString());
                if (Convert.ToDouble(_dtScore.Rows[i]["AverageScoreFinal"].ToString()) >= DefaultConfig.MinScorePass_NoYearly)
                {
                    _dCreditAcc += Convert.ToDouble(_dtScore.Rows[i]["TotalCredits"].ToString());
                    _dScoreAcc += Convert.ToDouble(_dtScore.Rows[i]["HPTC"].ToString());
                }
                _dCredit += Convert.ToDouble(_dtScore.Rows[i]["TotalCredits"].ToString());
                _dScore += Convert.ToDouble(_dtScore.Rows[i]["HPTC"].ToString());
            }
            double averageScoreAcc = 0;
            if (_dScoreAcc != 0)
            {
                averageScoreAcc = Math.Round(_dScoreAcc / _dCreditAcc, 2, MidpointRounding.AwayFromZero);
            }
            double averageScore = 0;
            if (_dScore != 0)
            {
                averageScore = Math.Round(_dScore / _dCredit, 2, MidpointRounding.AwayFromZero);
            }
            Training_Student_ClassInfo infoStudentClass = new Training_Student_ClassInfo(_strStudentId);
            infoStudentClass.Properties.AverageScoreAccumulate = averageScoreAcc;
            infoStudentClass.Properties.AverageScoreNoAccumulate = averageScore;
            infoStudentClass.Properties.TotalCreditAccumulate = _dCreditAcc;
            infoStudentClass.Save();
        }
        /// <summary>
        /// Lay thong tin nguoi yeu câu
        /// </summary>
        private void GetInfo()
        {
            if (m_bCheck == true)
            {
                txtpersonelName.Text = "";
                txtDateRequired.Text = "";
                txtReason.Text = "";
                txtFeedback.Text = "";
                try
                {
                    txtpersonelName.Text = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["personelName"]).ToString();
                    txtDateRequired.Text = Convert.ToDateTime(grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["DateCreate"]).ToString()).ToString("dd/MM/yyyy");
                    txtReason.Text = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Reason"]).ToString();
                    txtFeedback.Text = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Feedback"]).ToString();
                    m_strIDLogAdd = grvListLogAdd.GetRowCellValue(this.grvListLogAdd.FocusedRowHandle, grvListLogAdd.Columns["logAddID"]).ToString();
                    if ((bool)grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Status"]) == true)
                    {
                        txtFeedback.Enabled = false;
                        txtFeedback.Text = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Feedback"]).ToString();
                    }
                    else
                    {
                        txtFeedback.Enabled = true;
                    }
                }
                catch { }
            }
            else
            {
                try
                {
                    txtpersonelName.Text = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["personelName"]).ToString();
                    txtDateRequired.Text = Convert.ToDateTime(grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["DateCreate"]).ToString()).ToString("dd/MM/yyyy");
                    txtReason.Text = grvListLogAdd.GetFocusedRowCellValue(grvListLogAdd.Columns["Reason"]).ToString();
                    m_strIDLogAdd = grvListLogAdd.GetRowCellValue(this.grvListLogAdd.FocusedRowHandle, grvListLogAdd.Columns["logAddID"]).ToString();
                    txtFeedback.Enabled = true;
                }
                catch { }
            }
        }
    }
}